import { Directive, ElementRef, OnInit, Input } from '@angular/core';

declare var window: any;

@Directive({
    selector: '[cmbRippleButton]'
})
export class RippleButtonDirective implements OnInit {
    canvas: any;
    containers;
    elementRef: ElementRef;

    @Input() isRipple = false;

    constructor(element: ElementRef) {
        this.elementRef = element;
    }

    ngOnInit(): void {
        if (this.isRipple) {
            this.init(this.elementRef.nativeElement);
        }
    }

    private init(ele) {
        this.canvas = document.createElement('canvas');
        this.canvas.addEventListener('click', this.press, false);
        ele.appendChild(this.canvas);
        this.canvas.style.width = '100%';
        this.canvas.style.height = '100%';
        this.canvas.style.position = 'absolute';
        this.canvas.style.top = '0';
        this.canvas.style.left = '0';
        this.canvas.style.opacity = '0.2';
        this.canvas.width = this.canvas.offsetWidth;
        this.canvas.height = this.canvas.offsetHeight;
    }

    private press(event) {
        const color = 'white'; // $(event.toElement.parentElement).css('backgroundColor');
        const element = event.toElement;
        const context = element.getContext('2d');
        let radius = 0;
        const centerX = event.offsetX;
        const centerY = event.offsetY;
        context.clearRect(0, 0, element.width, element.height);
        const raf = requestAnimFrame();
        draw();

        function draw() {
            context.beginPath();
            context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
            context.fillStyle = color;
            context.fill();
            radius += 6;
            if (radius < element.clientWidth) {
                raf(draw);
            } else {
                context.clearRect(0, 0, element.width, element.height);
            }
        }

        function requestAnimFrame() {
            return (
                window.requestAnimationFrame ||
                window.mozRequestAnimationFrame ||
                window.oRequestAnimationFrame ||
                window.msRequestAnimationFrame ||
                function (callback) {
                    window.setTimeout(callback, 1000 / 60);
                }
            );
        }
    }

}
